import React, {useEffect, useState} from 'react';
import {Form, Input, Modal, Tree} from 'antd';
import {queryRoleMenuList} from "../service";
import type {RoleListItem, updateRoleMenuListParams} from "@/pages/system/RoleList/data";
import {tree} from "@/utils/utils";

interface UpdateUserFormProps {
  open: boolean;
  onCreate: (values: updateRoleMenuListParams) => void;
  onCancel: () => void;
  item?: RoleListItem;
}

const SetRoleMenuForm: React.FC<UpdateUserFormProps> = ({open, onCreate, onCancel, item}) => {
  const [form] = Form.useForm();
  const FormItem = Form.Item;

  const [treeData, setTreeData] = useState([]);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);

  useEffect(() => {
    if (open) {
      if (item) {
        form.setFieldsValue(item);
      }
      setCheckedKeys([]);
      queryRoleMenuList({roleId: item?.id || 0}).then((res) => {
        // @ts-ignore
        setTreeData(tree(res.data.menuList, 0, "parentId"))
        if (res.data.menuIds) {
          setCheckedKeys(res.data.menuIds);
        }
      })
    }

  }, [open]);

  const handleOk = () => {
    const menuIds = checkedKeys.map((i) => Number(i))
    onCreate({roleId: item?.id || 0, menuIds})
  }

  const onCheck = (checkedKeysValue: React.Key[]) => {
    setCheckedKeys(checkedKeysValue);
  };

  const roleFormContent = () => {
    return (
      <>
        <FormItem
          label="id"
          name="id"
          hidden={true}
        >
          <Input/>
        </FormItem>
        <Tree
          checkable
          // @ts-ignore
          onCheck={onCheck}
          checkedKeys={checkedKeys}
          treeData={treeData}
          fieldNames={{title: 'menuName', key: 'id', children: 'children'}}
        />
      </>
    )
  }

  const modalFooter = {title: "更新", okText: '保存', onOk: handleOk, onCancel, cancelText: '取消', open, width: 480};
  const formLayout = {labelCol: {span: 7}, wrapperCol: {span: 13}, form};

  return (
    <Modal {...modalFooter} style={{top: 150}}>
      <Form {...formLayout} style={{marginTop: 30}}>
        {roleFormContent()}
      </Form>
    </Modal>
  );
};

export default SetRoleMenuForm;
